<template>
  <el-container style="height: 98vh; border: 1px solid #eee;background: #fff">
     <SideBar />
	 <el-container >
		<el-header style="width: 95%;margin-top: 10px;">
			<HeadBar/>
		</el-header>
	    <el-main>
			<div style="margin: 40px;">
				<el-button  @click="getCourseByGrade" type="primary" round style="margin-left:40px;">查看所有课程</el-button>
				<el-button  @click="getCourseRight" type="primary" round style="margin-left:40px;">查看所有可选课程</el-button>
				<el-button  @click="getConflict" type="primary" round style="margin-left:40px;">查看已冲突课程</el-button>
				<el-button  @click="getChosenCourse" type="primary" round style="margin-left:40px;">查看已选课程</el-button>
			</div>
			
			<el-table :data="tableData" stripe style="width: 100%;text-align: center;"  border>
				<el-table-column fixed prop="coursename" label="课程名" align="center" ></el-table-column>
				<el-table-column prop="teacher" label="授课老师" align="center"> </el-table-column>
				<el-table-column prop="room" label="教室" align="center">  </el-table-column>
				<el-table-column  label="上课时间" align="center">
					<template slot-scope="{ row }">
					    星期{{ row.weekday }} 第{{ row.startTime }}小节至第{{ row.endTime }}小节
					  </template>
				</el-table-column>
				<el-table-column label="操作" align="center"> 
				  <template slot-scope="{ row }">
				    <el-button 
				      :type="isCourseChosen(row) ? 'danger' : 'primary'"
				      :disabled="!isCourseChosen(row) && isConflict(row)"
				      @click="isCourseChosen(row) ? handleDrop(row) : handleSelect(row)"
				      size="big">
				      {{ getButtonText(row) }}
				    </el-button>
				  </template>
				</el-table-column>
			</el-table>
	    </el-main>
	  </el-container>
	
	
  </el-container>
</template>

<script>
import SideBar from '@/components/SideBar.vue'
import HeadBar from '@/components/HeadBar.vue'
import request from "@/utils/request";

export default {
  components:{SideBar,HeadBar},
  data() {
    return {
      academicYear: null,
	  studentId: sessionStorage.getItem("studentId"),
	  tableData:[],
	  conflictCourses: [],
	  chosenCourses: [],
	  currentView: 'all',
    }
  },
  mounted() {
    this.loadFromStorage();
    this.getChosenCourse(); // 新增初始化加载
	this.getCourseByGrade();
  },
  methods: {
    loadFromStorage() {
      const data = JSON.parse(sessionStorage.getItem('semester_info'))
      this.academicYear = data
    },
	async getCourseByGrade() {
	      this.currentView = 'all';
	      const url = `/course/getCourseByGrade?studentId=${this.studentId}&academicYear=${this.academicYear.academicYear}&semester=${this.academicYear.semester}`;
	      const res = await request.get(url);
	      this.tableData = res.data.data;
	    },
	async getCourseRight() {
	      this.currentView = 'available';
	      const url = `/course/getGradeRightCourses?studentId=${this.studentId}&academicYear=${this.academicYear.academicYear}&semester=${this.academicYear.semester}`;
	      const res = await request.get(url);
	      this.tableData = res.data.data;
	    },
	async getChosenCourse() {
	      this.currentView = 'chosen';
	      const url = `/course/getChosenCourse?studentId=${this.studentId}`;
	      const res = await request.get(url);
	      this.chosenCourses = res.data.data;
	      this.tableData = res.data.data;
	    },
	async getConflict() {
	      this.currentView = 'conflict';
	      const url = `/course/getGradeConflictCourses?studentId=${this.studentId}&academicYear=${this.academicYear.academicYear}&semester=${this.academicYear.semester}`;
	      const res = await request.get(url);
	      this.conflictCourses = res.data.data;
	      this.tableData = res.data.data;
	    },
	isConflict(currentCourse) {
	    return this.conflictCourses.some(course => 
	      course.weekday === currentCourse.weekday &&
	      Math.max(course.startTime, currentCourse.startTime) < 
	      Math.min(course.endTime, currentCourse.endTime)
	    );
	  },
	async refreshData() {
	      switch(this.currentView) {
	        case 'all':
	          await this.getCourseByGrade();
	          break;
	        case 'available':
	          await this.getCourseRight();
	          break;
	        case 'conflict':
	          await this.getConflict();
	          break;
	        case 'chosen':
	          await this.getChosenCourse();
	          break;
	        default:
	          await this.getCourseByGrade();
	      }
	      // 无论当前视图如何都需要更新冲突数据
	      await this.updateConflictData();
	    },
	async updateConflictData() {
	      const url = `/course/getGradeConflictCourses?studentId=${this.studentId}&academicYear=${this.academicYear.academicYear}&semester=${this.academicYear.semester}`;
	      const res = await request.get(url);
	      this.conflictCourses = res.data.data;
	    },
	async handleSelect(row) {
	      try {
	        const url = `/course/chooseCourse?courseid=${row.courseid}&studentId=${this.studentId}`;
	        await request.get(url);
	        
	        await Promise.all([
	          this.refreshData(),      // 使用统一刷新方法
	          this.getChosenCourse()  // 强制更新已选课程列表
	        ]);
	        
	        this.$message.success('选课成功');
	      } catch (error) {
	        this.$message.error('选课失败');
	      }
	    },
	// 判断课程是否已选
	isCourseChosen(currentCourse) {
	    return this.chosenCourses.some(
	    c => c.courseid === currentCourse.courseid
		);
	},
	  // 获取按钮显示文本
	getButtonText(row) {
	    if (this.isCourseChosen(row)) {
	    return '退课';
	    }
	    return this.isConflict(row) ? '不可选' : '立即选课';
	},
	async handleDrop(row) {
	      try {
	        const url = `/course/deleteCourse?courseid=${row.courseid}&studentId=${this.studentId}`;
	        await request.get(url);
	        
	        await this.refreshData();
	        this.$message.success('退课成功');
	      } catch (error) {
	        this.$message.error('退课失败: ' + error.response?.data?.message || '');
	      }
	}
  }
}
</script>

<style>
</style>